package com.arvato.minipro.controller.front.mall;


import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.arvato.minipro.bean.bean_do.mall.EcAddressDo;
import com.arvato.minipro.bean.bean_dto.common.PageData;
import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.minipro.service.mall.AddressService;

/**
 * 
 * @author: smallking
 * 
 * @Descibe:用户收货地址Controller
 * 
 * @Date: 2018年5月8日  上午11:24:50
 */
@Controller
@RequestMapping(value = "/mall/address")
public class AddressController {
	
	@Autowired
	private AddressService addressService;
	
	/**
	 * 按照条件查询多条收货地址
	 * @param req
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list", method = {RequestMethod.POST})
	public PageData list(HttpServletRequest req, @RequestParam Map<String, Object> param) {
		String userId = req.getParameter("userId");
		if(userId == null) {
			return null;
		}
		Query query = new Query(param);
		PageData data = addressService.listAddressByQuery(query);
		if(query.get("defaultAddress") != null && data.getData().size() == 0) {
			// 如果没有默认地址 那么就返回列表的第一个
			query.remove("defaultAddress");
			data = addressService.listAddressByQuery(query);

		}
		data.setFront(true);
		return data;
	}
	
	/**
	 * 新增一个收货地址
	 * @param req
	 * @param addressDo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/insert", method = {RequestMethod.POST})
	public Result insert(HttpServletRequest req, EcAddressDo addressDo){
		Result result = new Result(false);
		String userId = req.getParameter("userId");
		if(userId == null) {
			return result;
		}
		addressDo.setCreateTime(new Date());
		try {
			int row = addressService.insert(addressDo);
			if(row == 1) {
				result.setResult(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 修改收货地址
	 * @param req
	 * @param addressDo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = {RequestMethod.POST})
	public Result update(HttpServletRequest req, EcAddressDo addressDo){
		Result result = new Result(false);
		addressDo.setUpdateTime(new Date());
		try {
			int row = addressService.update(addressDo);
			if(row == 1) {
				result.setResult(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
}
